package com.yb.forum.controller;


import com.yb.forum.common.AppResult;
import com.yb.forum.common.ResultCode;
import com.yb.forum.config.AppConfig;
import com.yb.forum.model.Article;
import com.yb.forum.model.Board;
import com.yb.forum.model.User;
import com.yb.forum.services.IArticleService;
import com.yb.forum.services.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "文章接口")
@RequestMapping("/article")
@Slf4j
@RestController
public class ArticleController {

    @Resource
    private IBoardService boardService;
    @Resource
    private IArticleService articleService;
    /**
     * 发布新帖子
     * @param boardId 板块ID
     * @param title 标题
     * @param content 内容
     * @return AppResult
     */
    @ApiOperation("发布新帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
            @ApiParam("板块id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content)
    {
        // 校验用户的禁言状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            // 说明被禁言了
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 校验板块是否存在
        Board board = boardService.selectById(boardId);
        if(board == null || board.getDeleteState() == 1|| board.getState() == 1){
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString() + "板块状态异常, boardId = "+ board);
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        // 校验
        // 封装文章对象
        Article article = new Article();

        article.setContent(content);
        article.setTitle(title);
        article.setBoardId(boardId);
        article.setUserId(user.getId());

        // 调用service
        articleService.create(article);
        // 相应成功
        return AppResult.success();
    }
}
